import {
	computed
} from 'vue';
import {
	useStore
} from 'vuex';
import createApi from '../api/commonAPI.js';
import {
	REQUEST_SUCCESS
} from '../utils/config.js';
// import nid from 'nid';
export function useCommon() {
	const store = useStore();
	//这里需要把store传递给api
	const commonAPI = createApi(store);
	// 创建计算属性来封装 Vuex 状态
	const appid = computed(() => store.state.common.appid);
	const qnUpToken = computed(() => store.state.common.qnUpToken);
	const qiniuDomain = computed(() => store.state.common.qiniuDomain);
	const systemInfo = computed(() => store.state.common.systemInfo);
	const statusHeight = computed(() => store.state.common.statusHeight);
	const navHeight = computed(() => store.state.common.navHeight);
	const tabbarShow = computed(() => store.state.common.tabbarShow);
	const tabbarIndex = computed(() => store.state.common.tabbarIndex);
	const tabbarHeight = computed(() => store.state.common.tabbarHeight);
	const bottomSafeHeight = computed(() => store.state.common.bottomSafeHeight);
	const isAndroid = computed(() => store.state.common.isAndroid);
	const projectStatusMap = computed(() => store.state.common.projectStatusMap);
	const projectSiteTypeMap = computed(() => store.state.common.projectSiteTypeMap);
	const projectPresettingeMap = computed(() => store.state.common.projectPresettingeMap);
	const projectTypeMap = computed(() => store.state.common.projectTypeMap);
	const sporadicTypeMap = computed(() => store.state.common.sporadicTypeMap);
	const workTypeMap = computed(() => store.state.common.workTypeMap);
	const constructionUnit = computed(() => store.state.common.constructionUnit);
	const noImageKey = computed(() => store.state.common.noImageKey);
	const SET_APPID = (appid) => {
		store.commit('common/SET_APPID', appid);
	};
	const SET_QN_UP_TOKEN = (qnUpToken) => {
		store.commit('common/SET_QN_UP_TOKEN', qnUpToken);
	};
	const SET_SYSTEM_INFO = (systemInfo) => {
		store.commit('common/SET_SYSTEM_INFO', systemInfo);
	};
	const SET_NAV_SIZE = () => {
		store.commit('common/SET_NAV_SIZE');
	};
	const SET_IS_ANDROID = (isAndroid) => {
		store.commit('common/SET_IS_ANDROID',isAndroid);
	};
	const SET_PROJECT_SITE_TYPE = (projectSiteTypeMap) => {
		store.commit('common/SET_PROJECT_SITE_TYPE',projectSiteTypeMap);
	};
	const SET_PROJECT_PRESETTING = (projectPresettingeMap) => {
		store.commit('common/SET_PROJECT_PRESETTING',projectPresettingeMap);
	};
	const SET_PROJECT_TYPE = (projectTypeMap) => {
		store.commit('common/SET_PROJECT_TYPE',projectTypeMap);
	};
	const SET_SPORADIC_TYPE = (sporadicTypeMap) => {
		store.commit('common/SET_SPORADIC_TYPE',sporadicTypeMap);
	};
	const SET_WORK_TYPE = (workTypeMap) => {
		store.commit('common/SET_WORK_TYPE',workTypeMap);
	};
	const SET_CONSTRUCTION_UNIT = (constructionUnit) => {
		store.commit('common/SET_CONSTRUCTION_UNIT',constructionUnit);
	};
	const SET_TABBAR_INDEX = (tabbarIndex) => {
		store.commit('common/SET_TABBAR_INDEX',tabbarIndex);
	};
	const SET_TABBAR_SHOW = (tabbarShow) => {
		store.commit('common/SET_TABBAR_SHOW',tabbarShow);
	};
	const SET_TABBAR_HEIGHT = (tabbarHeight) => {
		store.commit('common/SET_TABBAR_HEIGHT',tabbarHeight);
	};
	
	const getQnUpToken = async (code) => {
		return new Promise((resolve, reject) => {
			try {
				commonAPI.qnUptoken({
				}).then((res) => {
					let data = res.data
					if (res.code === REQUEST_SUCCESS) {
						if (data.uptoken) {
							SET_QN_UP_TOKEN(data.uptoken)
						}
					}
					resolve(data)
				})
			} catch (error) {
				reject(res)
			}
		});
	};
	const reloadAllSystemInfo = async (code) => {
		if(navHeight.value===0){
			const systemInfo = await wx.getSystemInfoSync()
			SET_SYSTEM_INFO(systemInfo)
			if (systemInfo != undefined) {
				SET_NAV_SIZE()
			}
			// 检测是否为安卓设备
			if (/android/i.test(systemInfo.system)) {
				SET_IS_ANDROID(true)
			}
		}
	};
	const getProjectSiteType = async () => {
		return new Promise((resolve, reject) => {
			try {
				commonAPI.dicData({dictType:"project_site_type"}).then((res) => {
					let data = res.data
					if (res.code === REQUEST_SUCCESS) {
						if (data) {
							SET_PROJECT_SITE_TYPE(data)
						}
					}
					resolve(data)
				})
			} catch (error) {
				reject(res)
			}
		});
	};
	
	
	const deleteQN = async (deleteKey) => {
		return new Promise((resolve, reject) => {
			try {
				commonAPI.deleteQN({key:deleteKey}).then((res) => {
					let data = res.data
					if (res.code === REQUEST_SUCCESS) {
						if (data) {
							
						}
					}
					resolve(data)
				})
			} catch (error) {
				reject(res)
			}
		});
	};
	const uploadQN = async (fileUrl,fileFormData) => {
		return new Promise((resolve, reject) => {
			try {
				commonAPI.uploadQN(fileUrl,fileFormData).then((res) => {
					let data = res.data
					if (res.code === REQUEST_SUCCESS) {
						if (data) {
							
						}
					}
					resolve(data)
				})
			} catch (error) {
				reject(res)
			}
		});
	};
	
	
	const commonDeletePic = (event,fileList) => {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: '提示',
				content: '删除图片',
				success: function (res) {
					if (res.confirm) {
						if(event.file.qnKey){
							deleteQN(event.file.qnKey).then((resData)=>{
								 fileList.value.splice(event.index, 1);
								 resolve()
							}).catch((error)=>{
								reject()
							})
						}
					}
				}
			})
		})
	};
	const commonAfterRead = async (event,fileList,key,extParams) => {
		uni.showLoading({
			title: '上传中',
			mask: true
		})
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = fileList.value.length;
	  let fileExts=[]
	  lists.map((item) => {
		  let url=item.url
		  if(url){
			  const postfix = url.split('.').pop();
			  const timestampPart = Date.now().toString();
			  const fileNmae=timestampPart+nid();
			  const fullFile = fileNmae +'.'+postfix
			  fileExts.push({
			  	fullFile,
				key: key + fullFile
			  })
			  fileList.value.push({
			    ...item,
			    status: 'uploading',
			    message: '上传中',
			  });
		  }
	  });
	  
	  for (let i = 0; i < lists.length; i++) {
	    await uploadQN(lists[i].url,fileExts[i]).then((resData)=>{
			let qnKey=resData.key
			let item = fileList.value[fileListLen];
			let url=qiniuDomain.value+qnKey
			if(extParams&&extParams!=''){
				url+=extParams
			}
			fileList.value.splice(fileListLen, 1, {
			  ...item,
			  status: 'success',
			  message: '',
			  url,
			  qnKey,
			  extParams:(extParams&&extParams!='')?extParams:''
			});
			fileListLen++;
		})
	  }
	  uni.hideLoading()
	};
	const commonInitFileList =  (value,fileList) => {
		if(value!=undefined&&value!=''){
			//如果value里面的逗号前为空，则删除该项
			value=value.replace(/(^,)|(,$)/g, "")
			const qnKeyArray = value.split(',');
			const jsonFileArray = qnKeyArray.map(item => {
			    // 使用正则表达式分割字符串
			    let [qnKey, extParams] = item.split('?');
				if(extParams&&extParams!=''){
					extParams='?'+extParams
				}
				let url=qiniuDomain.value+qnKey
				if(extParams&&extParams!=''){
					url+=extParams
				}
			    return {
			        qnKey: qnKey,
			        url,
			        extParams: extParams || '', // 如果没有找到extParams则为空字符串
			        status: 'success'
			    }
			});
			fileList.value=jsonFileArray
		}
	};
	const commonFileList2Str =  (fileList) => {
		let fileStr=''
		if(fileList.value!=undefined&&fileList.value.length>0){
			let qnKeys = fileList.value.map(item => {
			    return (item.extParams&&item.extParams!='') ? `${item.qnKey}${item.extParams}` : item.qnKey;
			});
			fileStr=qnKeys.join(",")
		}
		return fileStr
	};
	
	const commonDeletePicValue = (event,fileList) => {
		return new Promise((resolve, reject) => {
			uni.showModal({
				title: '提示',
				content: '删除图片',
				success: function (res) {
					if (res.confirm) {
						if(event.file.qnKey){
							deleteQN(event.file.qnKey).then((resData)=>{
								 fileList.splice(event.index, 1);
								 resolve()
							}).catch((error)=>{
								reject()
							})
						}
					}
				}
			})
		})
	};
	const commonAfterReadValue = async (event,fileList,key,extParams) => {
		uni.showLoading({
			title: '上传中',
			mask: true
		})
	  // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = fileList.length;
	  let fileExts=[]
	  lists.map((item) => {
		  let url=item.url
		  if(url){
			  const postfix = url.split('.').pop();
			  const timestampPart = Date.now().toString();
			  const fileNmae=timestampPart+nid();
			  const fullFile = fileNmae +'.'+postfix
			  fileExts.push({
			  	fullFile,
				key: key + fullFile
			  })
			  fileList.push({
			    ...item,
			    status: 'uploading',
			    message: '上传中',
			  });
		  }
	  });
	  
	  for (let i = 0; i < lists.length; i++) {
	    await uploadQN(lists[i].url,fileExts[i]).then((resData)=>{
			let qnKey=resData.key
			let item = fileList[fileListLen];
			let url=qiniuDomain.value+qnKey
			if(extParams&&extParams!=''){
				url+=extParams
			}
			fileList.splice(fileListLen, 1, {
			  ...item,
			  status: 'success',
			  message: '',
			  url,
			  qnKey,
			  extParams:(extParams&&extParams!='')?extParams:''
			});
			fileListLen++;
		})
	  }
	  uni.hideLoading()
	};
	const commonInitFileListValue =  (value) => {
		let fileList=[]
		if(value!=undefined&&value!=''){
			const qnKeyArray = value.split(',');
			const jsonFileArray = qnKeyArray.map(item => {
			    // 使用正则表达式分割字符串
			    let [qnKey, extParams] = item.split('?');
				if(extParams&&extParams!=''){
					extParams='?'+extParams
				}
				let url=qiniuDomain.value+qnKey
				if(extParams&&extParams!=''){
					url+=extParams
				}
			    return {
			        qnKey: qnKey,
			        url,
			        extParams: extParams || '', // 如果没有找到extParams则为空字符串
			        status: 'success'
			    }
			});
			fileList=jsonFileArray
		}
		return fileList
	};
	const commonFileList2StrValue =  (fileList) => {
		let fileStr=''
		if(fileList!=undefined&&fileList.length>0){
			let qnKeys = fileList.map(item => {
			    return (item.extParams&&item.extParams!='') ? `${item.qnKey}${item.extParams}` : item.qnKey;
			});
			fileStr=qnKeys.join(",")
		}
		return fileStr
	};
	const previewimageArray =  (imgArray,index) => {
		let urls = []
		imgArray.forEach(item => {
			urls.push(item)
		})
		if(!index){
			index=0
		}
		let current=urls[index]
		uni.previewImage({
			urls,
			current
		});
	};
	return {
		appid,
		qnUpToken,
		qiniuDomain,
		systemInfo,
		statusHeight,
		navHeight,
		tabbarShow,
		tabbarIndex,
		tabbarHeight,
		bottomSafeHeight,
		isAndroid,
		getQnUpToken,
		noImageKey,
		projectStatusMap,
		projectSiteTypeMap,
		projectPresettingeMap,
		projectTypeMap,
		sporadicTypeMap,
		workTypeMap,
		constructionUnit,
		SET_TABBAR_INDEX,
		SET_TABBAR_SHOW,
		SET_TABBAR_HEIGHT,
		getProjectSiteType,
		reloadAllSystemInfo,
		uploadQN,
		deleteQN,
		commonDeletePic,
		commonAfterRead,
		commonInitFileList,
		commonFileList2Str,
		previewimageArray,
		commonDeletePicValue,
		commonAfterReadValue,
		commonInitFileListValue,
		commonFileList2StrValue,
	};
}